﻿using System;
using GearOptimizer.Adapters;
using GearOptimizer.DataObjects;
using GearOptimizer.Factories;
using StructureMap;

namespace GearOptimizer.Services
{
    public class CharacterService
    {
        private readonly IBattleNetAdapter battleNetAdapter;
        private readonly IRepositoryFactory repositoryFactory;

        public CharacterService(IBattleNetAdapter battleNetAdapter)
        {
            this.battleNetAdapter = battleNetAdapter;
            repositoryFactory = ObjectFactory.GetInstance<IRepositoryFactory>();
        }

        public Character LoadProfile(string characterName, string realmName)
        {

            var repository = repositoryFactory.GetRepository<Character>();
            if (!repository.Contains(characterName + realmName))
            {
                var characterProfile = battleNetAdapter.RetrieveCharacterProfile(characterName, realmName);
                repository.Set(characterProfile);
                return characterProfile;
            }
            return repository.Get(characterName + realmName);
        }

        public Result SaveCharacter(Character character)
        {

            var repository = repositoryFactory.GetRepository<Character>();
            if (character == null)
            {
                return new Result{Success = false};
            }
            try
            {
                repository.Set(character);
            }
            catch (Exception)
            {
                return new Result{Success = false};
            }

            return new Result {Success = true};
        }

        public Result AddItemToSlot(string characterName, string realmName, SlotNames slotName, string itemId)
        {
            var itemService = new ItemService();
            var item = itemService.LoadItem(itemId);

            var result = new Result {Success = true};
            if ((SlotNames) item.InventoryType != slotName)
            {
                result.Success = false;
                return result;
            }

            var character = LoadProfile(characterName, realmName);
            character.AddItemToSlot(item, slotName);
            SaveCharacter(character);
            return result;
        }
    }

    public class Result
    {
        public bool Success { get; set; }
    }
}